package py.com.sole.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;


import py.com.sole.dao.DaoFactory;
import py.com.sole.dao.RolDao;

import py.com.sole.model.Rol;

public class RolImpl implements RolDao {
	EntityManager em = DaoFactory.getEm();

	public void addRol(Rol rol) {
		try {
			em.getTransaction().begin();
			em.persist(rol);
			em.getTransaction().commit();
		} catch (Exception e) {
			// System.out.println("Error al intentar persistir "+e);
			e.printStackTrace();
		}

	}

	public void deleteRol(int id) {
		try {
			em.getTransaction().begin();
			em.remove(this.getRolById(id));
			em.getTransaction().commit();
		} catch (Exception e) {
			
		}
	}

	public void updateRol(Rol rol) {
		try {
			em.getTransaction().begin();
			em.merge(this.getRolById(rol.getId()));
			em.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public Rol getRolById(int id) {

		return (Rol) em.createQuery(
				"SELECT r FROM Rol r where r.id = " + id).getSingleResult();
	}

	@SuppressWarnings(value = "all")
	public List<Rol> getRoles() {
		return em.createQuery("SELECT r FROM Rol r where r.activo=TRUE").getResultList();
	}

	@Override
	public Rol getRolByName(String value) {
		try {
			Query q = em.createNamedQuery("Rol.findByDescripcion");
			q.setParameter("descripcion", value);
			return (Rol) q.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

}
